package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CustomClassLoader extends ClassLoader {

    private String classDir;

    @Override
    public Class<?> findClass(String name) {

        String path = classDir + File.separator + name;
        path = path.replaceAll("\\.", "/") + ".class";
        path = path.replaceAll("\\\\", "/").replaceAll("/+","/");

        File file = new File(path);

        byte[] classBytes = null;
        try {
            FileInputStream in = new FileInputStream(file);
            classBytes = new byte[in.available()];
            int readSize = in.read(classBytes);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //调用父类的defineClass方法
        return defineClass(name, classBytes, 0, classBytes.length);
    }

    public CustomClassLoader(String classDir) {
        this.classDir = classDir;
    }
}
